import $ from 'jquery';
import React from 'react';
import classnames from 'classnames';
import _ from 'underscore';
import Modal from 'lib/components/Modal.jsx';
import Select from 'lib/components/Select.jsx';
import ApiFactory from 'lib/ApiFactory';
import tooltip from 'lib/components/tooltip.jsx';
import { coreApi } from '../apis/core-util';
import { Success, Warning } from 'lib/components/Notify.jsx';
import CopyClipboard from 'lib/components/CopyClipboard.jsx';

class ElementModal extends Modal {

  constructor(props, context) {
    super(props, context);

    let keys = [
        'id', 'name', 'priority', 'conditions'
      ];

    this.state = Object.assign({}, {
      message: '',
      urlMessage: '',
      name: '',
      priority: 1,
      saving: false,
      conditions: {
        'http.url': {
          value: '',
          operatorCode: 101
        },
        'http.method': {
          value: 'GET',
          operatorCode: 101
        }
      }
    }, _.pick(props, ...keys));
  }

  renderHeader() {
    return (
      <h4> {this.props.id ? '编辑关键请求' : '添加关键请求'}</h4>
    );
  }

  /**
   * 处理数据提交（新增/更新）.
   * 
   * @return {Undefined}
   */
  handleSubmit() {
    if (!this.state.name) {
      this.setState({
        message: '请输入关键元素名称'
      });
      return false;
    }

    if (this.state.name.length >= 100) {
      this.setState({
        message: '关键元素名称不能超过100个字符'
      });
      return false;
    }

    if (!this.state.conditions['http.url'].value) {
      this.setState({
        urlMessage: '请输入URL'
      });
      return false;
    }

    if (this.state.conditions['http.url'].value.length >= 250) {
      this.setState({
        urlMessage: 'URL长度不能超过255个字符'
      });
      return false;
    }

    this.setState({
      saving: true
    });

    $.ajax({
      url: this.props.id ? `${BlueWare.urlPrefix}/app/${BlueWare.appId}/keytransaction/${this.props.id}.json` : `${BlueWare.urlPrefix}/app/${BlueWare.appId}/keytransaction.json`,
      type: this.props.id ? 'PUT' : 'POST',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(this.state)
    }).success((res) => {
      if (res.status === 'SUCC') {
        Success('操作成功！');
        location.reload();
      } else {
        // 消息提示
        Warning(res.reason);

        this.setState({
          saving: false
        });
      }
    });
  }

  /**
   * 响应用户数据输入.
   * 
   * @param  {String}         key1    上一级
   * @param  {Object|Number}  key2    事件对象/select回掉参数/键名
   * @param  {Object}         event   事件对象
   * @return {Undefined}
   */
  handleChange(key1, key2, event) {
    let { message } = this.state;

    if (/^http/i.test(key1)) {
      let { conditions, urlMessage } = this.state,
          target = (event.target || event),
          value = key2 === 'operatorCode' ? +target.value : target.value.trim();
      conditions[key1][key2] = value;

      if (key1 === 'http.url') {
        if ( value.length > 0 || value.length < 250 ) {
          urlMessage = null;
        }
      }

      this.setState({
        conditions,
        urlMessage
      });
    } else {
      let target = (key2.target || key2),
          value = ('' + target.value).trim();

      if (key1 === 'name') {
        this.setState({
          message: value.length === 0 ? '不合法的请求名称' : null,
          [key1]: value
        });
      } else {
        this.setState({
          [key1]: value
        });
      }
    }
  }

  handleCopyRegExp() {
    window.open('http://tool.chinaz.com/regex/');
  }

  renderBody() {
    let { conditions } = this.state;

    return (
      <div className="element-setting-modal" style={{width: 660}}>
        <div className="form-group horizontal">
          <ul>
            <li style={{marginBottom: 0}}>
              <label className="control-label">请求名称</label>
              <input type="text" className="input-text" defaultValue={ this.props.name } onChange={ this.handleChange.bind(this, 'name') } />
              <span className="input-addon text-red">*</span>
              <span className="msg-error">{ this.state.message }</span>
            </li>
            <li>
              <label className="control-label">优先级</label>
              <Select
                style={{
                  width: 100,
                  float: 'left'
                }}
                options={_.range(1, 11).map((i) => {
                  return { label: '' + i, value: '' + i }
                })}
                value={ this.state.priority + '' }
                onChange={ this.handleChange.bind(this, 'priority') } />
              <span
                className="iconfont"
                style={{
                  color: '#555',
                  fontSize: 16,
                  lineHeight: '33px',
                  marginLeft: 10,
                  verticalAlign: 'top'
                }}
                data-tip="当两条规则有重叠时，数据将会导入优先级<br />较高（数值大）的关键请求。"
                data-place="right">&#xe663;</span>
            </li>
            <li style={{ marginBottom: 22 }}>
              <label className="control-label">请求方法</label>
              <Select style={{width: 100}} options={['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].map((value) => {
                return {label: value, value: value}
              })} value={ conditions['http.method'].value.toUpperCase() }
                onChange={ this.handleChange.bind(this, 'http.method', 'value') } />
            </li>
            <li>
              <label className="control-label" style={{ lineHeight: '24px' }}>URL</label>
              <div className="clearfix" style={{paddingBottom: 6}}>
                <span className="iconfont" style={{color: '#555', fontSize: 16}} data-tip="请输入完整请求信息或以正则表达式配置一类请求作为关键元素" data-place="right">&#xe663;</span>
              </div>
              <ul className="element-form-group url-info">
                <div className="input-radio-group clearfix">
                  <div className="radio">
                    <label>
                      <input type="radio" name="type" value="101" defaultChecked={ conditions['http.url'].operatorCode === 101 }
                        onChange={ this.handleChange.bind(this, 'http.url', 'operatorCode') } /> 文本匹配
                    </label>
                  </div>
                  <input type="text" className="input-text" value={ conditions['http.url'].operatorCode === 101 ? conditions['http.url'].value : '' }
                    style={{width: '100%'}} onChange={ this.handleChange.bind(this, 'http.url', 'value') } disabled={ conditions['http.url'].operatorCode !== 101 } />
                </div>
                <div className="input-radio-group clearfix" style={{marginBottom: 5}}>
                  <div className="radio">
                    <label>
                      <input type="radio" name="type" value="105" defaultChecked={ conditions['http.url'].operatorCode === 105 }
                        onChange={ this.handleChange.bind(this, 'http.url', 'operatorCode') } /> 正则表达式匹配
                    </label>
                  </div>
                  <textarea disabled={ conditions['http.url'].operatorCode !== 105 } onChange={ this.handleChange.bind(this, 'http.url', 'value') }
                     rows="4" value={ conditions['http.url'].operatorCode === 105 ? conditions['http.url'].value : '' }>
                  </textarea>
                </div>
                <div className="help-block">
                {
                  conditions['http.url'].operatorCode === 105 ? (
                    <CopyClipboard text={ conditions['http.url'].value }>
                      <a href="javascript:;" onClick={ this.handleCopyRegExp.bind(this) }>复制并验证表达式</a>
                    </CopyClipboard>
                  ) : <a href="javascript:;" className="text-disabled">复制并验证表达式</a>
                }
                </div>
              </ul>
              <div className="msg-error">{ this.state.urlMessage }</div>
            </li>
          </ul>
        </div>
      </div>
    );
  }

  renderFooter() {
    return (
      <button className="btn-green" onClick={ this.handleSubmit.bind(this) }>保存</button>
    );
  }
}

export default ElementModal;
